﻿using System;
using System.Collections.Generic;
using System.Configuration;
using HelpersDotNet.DomainDrivenDesign.Infrastructure.DomainBase;
using HelpersDotNet.DomainDrivenDesign.Infrastructure.EntityFactoryFramework.Configuration;

namespace HelpersDotNet.DomainDrivenDesign.Infrastructure.EntityFactoryFramework
{
    public static class EntityFactoryBuilder
    {
        private static Dictionary<string, object> _factories = new Dictionary<string, object>();

        public static IEntityFactory<T> BuildFactory<T>() where T : IEntity
        {
            IEntityFactory<T> factory = null;

            string key = typeof(T).Name;

            if (_factories.ContainsKey(key))
                factory = _factories[key] as IEntityFactory<T>;
            else
            {
                EntitySettings settings = (EntitySettings)ConfigurationManager.GetSection(
                    EntityMappingConstants.EntityMappingsConfigurationSectionName);

                Type entityFactoryType = Type.GetType(settings.EntityMappings[key].EntityFactoryFullTypeName);

                factory = Activator.CreateInstance(entityFactoryType) as IEntityFactory<T>;

                _factories.Add(key, factory);
            }
            return factory;
        }
    }
}
